package com.bookstore.fliter;

import com.bookstore.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = {"/pages/manager/manager.html",
        "/pages/edit/edit.html","/pages/order/order.html","/pages/cart/cart.html","/index.html"})
public class LoginFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //设置编码集，解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession();
        User user=(User)session.getAttribute("user");
        if(user!=null){
            chain.doFilter(request, response);
        }
//        req.getRequestDispatcher("pages/user/login.html").forward(request,response);
        ((HttpServletResponse) response).sendRedirect(req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/"+req.getContextPath()+"/pages/user/login.html");
    }
    
}
